const express = require('express')
const app = express()
// 导入WebSocket模块:
const WebSocket = require('ws');
// 引用Server类:
const WebSocketServer = WebSocket.Server;
// 实例化:
const wss = new WebSocketServer({
    port: 8085
});
let user={} //存储连接用户
let onLine = 0 //存储在线人数 
wss.on('connection', function (ws,req) {
    console.log(`[SERVER] connection()`);
	// console.log(ws,777);
	console.log(req.url,66);
	let i=1
	ws.send('已发送'+(++i))
	onLine=wss._server._connections
	// console.log(onLine,66);
    ws.on('message', function (message) {
        console.log(`[SERVER] Received: ${message}`);
        // ws.send(`ECHO: ${message}`, (err) => {
        //     if (err) {
        //         console.log(`[SERVER] error: ${err}`);
        //     }
        // });
		    // Broadcast to everyone else.

		wss.clients.forEach(function each(client) {
		      if (client !== ws && client.readyState === WebSocket.OPEN) {
		        client.send(message);
		      }
		    });
    })
});
wss.broadcast = function broadcast(data) {
  wss.clients.forEach(function each(client) {
    if (client.readyState === WebSocket.OPEN) {
      client.send(data);
    }
  });
};
// ws.on('pong', () => { console.log('server: received pong from client'); })//ws是通过ping/pong 心跳维护连接的

wss.clients.forEach(function(item){ //广播
 if(item._ultron.id==ws._ultron.id){return}
 // console.log(item._ultron) 
 item.send(JSON.stringify(arr)) 
     }) 
app.get('/', (req, res) => res.send('Hello World!'))

app.listen(3000, () => console.log('Example app listening on port 3000!'))